package service

import (
    "authserver/constants"
    "authserver/global"
    "authserver/model"
    "fmt"
    "math/rand"
    "time"
)

func AddShortUrl(username,realUrl string) (err error,res string) {

    var tempUrl model.ShortUrl

    shortUrl:=model.ShortUrl{
        RealUrl:    realUrl,
        Username:   username,
        RecordTime: time.Now().Format(constants.DayTime),
    }

    for ;; {
        shortKey:=GetRandomKey(7)

        global.GVA_DB.Table(shortUrl.TableName()).Where("short_key=?",shortKey).Find(&tempUrl)

        if tempUrl.Id!=0{
            fmt.Println("重复了...",shortKey)
            continue
        }
        shortUrl.ShortKey = shortKey
        break
    }

    err=global.GVA_DB.Create(&shortUrl).Error

    return nil,fmt.Sprintf("%s%s","http://st.bogerj.cn/st/",shortUrl.ShortKey)

}


func GetShortUrlByKey(shortKey string) (realUrl string) {

    var shortUrl model.ShortUrl

    global.GVA_DB.Table(shortUrl.TableName()).Where("short_key=?",shortKey).Find(&shortUrl)

    if shortUrl.Id!=0{
        return shortUrl.RealUrl
    }
    return ""



}


// 获取随机key
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

func GetRandomKey(length int) string {
    b := make([]byte, length)
    for i := range b {
        b[i] = charset[rand.Intn(len(charset))]
    }
    return string(b)

}

